package com.zyc.studentstudy.ui.youdao

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.lifecycle.lifecycleScope
import com.zyc.studentstudy.databinding.FragmentFanyiBinding
import com.zyc.studentstudy.simple.SimpleFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Created by zhangyuncai on 2025/10/14.
 * 描述：
 */
class FanyiFragment : SimpleFragment() {
    private val H5_JSCALL_NAME = "Android"
    private lateinit var mDB: FragmentFanyiBinding
    private var httpUrl = "https://m.youdao.com/translate"
    private val mWebView: WebView by lazy {
        mDB.webFanyi
    }

    override fun useDatabing(inflater: LayoutInflater, container: ViewGroup?): View? {
        mDB = FragmentFanyiBinding.inflate(inflater, container, false)
        return mDB.root
    }

    override fun lazyFetchData() {
    }

    override fun initView() {
        val jsCall = object : JsCall() {
            override fun callbackParam(param: String?) {

            }

        }
        mWebView.apply {
            settings.javaScriptEnabled = true
            settings.mediaPlaybackRequiresUserGesture = false
            webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                    view.loadUrl(url)
                    return true
                }
            }
            getSettings().setJavaScriptEnabled(true)
            addJavascriptInterface(
                jsCall,
                H5_JSCALL_NAME
            )
            loadUrl(httpUrl)
        }
    }

    ///点击翻译按钮
    fun clickFanyi() {
        viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Main) {

        }
    }

    ///输入翻译中的内容
    fun inputFanyiText(){
        val key="hello"
        mWebView.evaluateJavascript(
            "javascript:document.querySelector('#inputText').value='$key';",
            null
        )
        mWebView.evaluateJavascript(
            "javascript:document.querySelector('.blue-btn').click();",
            null
        )
    }

    override fun initEvent() {
    }

}